

#include "HeaderFiles.h"
#include "comm_struct.h"
#include "uart_comm_hdl.h"


STR_CHARGE batCharge;

/*!
    \brief      
    \param[in]  none
    \param[out] none
    \retval     none
*/

uint32_t est_charge_time(float32_t vbattery_bef)
{
	float32_t charge_time_h = 0;
	uint32_t charge_time_ms = 0;
	
	#if 1
	charge_time_h = (float32_t)((vbattery_bef * BAT_CHARGE_TIME_CAL_K) + BAT_CHARGE_TIME_CAL_B);
	#else
	charge_time_h = (float32_t)((vbattery_bef * (-1.25f)) + 20.625f);
	#endif
	
	charge_time_ms = (uint32_t)(charge_time_h * 60 * 60 * 10);
	
	return charge_time_ms;

}


/*!
    \brief      
    \param[in]  none
    \param[out] none
    \retval     none
*/
uint32_t est_over_time(float32_t vbattery_bef)
{
	uint32_t over_time = 0;
	
	

	return over_time;

}



/*!
    \brief      
    \param[in]  none
    \param[out] none
    \retval     none
*/

uint16_t battery_status_check(STR_CHARGE *hdl, float32_t vbattery, float32_t isbus)
{	
	hdl->gpio_level = CHARGE_STATUS_READ();
	
	hdl->vbattery_now = vbattery;
	hdl->isbus_now = isbus;
	
	if(hdl->gpio_level == 1)
	{
		hdl->status = BAT_STATUS_CHARGE;
		
		if(hdl->gpio_level_old == 0)
		{
			// enter the status of charge in first time, estimate charge time and over time
			hdl->waittime_est = est_charge_time(hdl->vbattery_bef);
			hdl->overtime_est = est_over_time(hdl->vbattery_bef);
		}
		
		hdl->waittime_cnt++;
		
		if((hdl->waittime_cnt > hdl->waittime_est) && (hdl->vbattery_now > BATTERY_RATE_100))
		{
			#if 0
			hdl->waittime_cnt = hdl->waittime_est;
			hdl->status = BAT_STATUS_CHARGE_FULL;	
			#endif
		}
		
		else if(hdl->waittime_cnt > hdl->overtime_est)
		{
			;
		}
		
		// Detect the ibus current change rate within 1 minute 
		hdl->isbus_diff = hdl->isbus_now - hdl->isbus_old;
		
		// wait time interval reach 1 minute
		if(hdl->waittime_cnt % 600 == 1)
		{
			hdl->isbus_old = hdl->isbus_now;
		}
		
		// Detect the vbattery reach FULL voltage value
		// Detect the ibus current change rate less than 100mA
		// Detect the ibus current now less than 300mA
		if((hdl->vbattery_now > BATTERY_CHARGE_FULL)              &&     \
			(fabsf(hdl->isbus_diff) < CHARGE_CURRENT_FULL_DIFF)   &&     \
			 (fabsf(hdl->isbus_now) < CHARGE_CURRENT_FULL_VALUE))
		{
			hdl->hold_cnt++;
			
			if(hdl->hold_cnt > CHARGE_FULL_CNT_THRE)
			{
				hdl->hold_cnt = CHARGE_FULL_CNT_THRE;
				hdl->status = BAT_STATUS_CHARGE_FULL;		
			}
		}
		else
		{
			hdl->hold_cnt = 0;		
		}
	}
	else
	{
		hdl->status = BAT_STATUS_UNCHARGE;
		hdl->vbattery_bef = vbattery;
		
		hdl->waittime_cnt = 0;
		hdl->hold_cnt = 0;
	}
	
	hdl->gpio_level_old = hdl->gpio_level;
	
	return hdl->status;
}

